package fragments;


import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.example.administrator.baseproject.BaseFragment;
import com.example.administrator.newxlmedical.R;

import beans.NewUserInfoBean;
import beans.PutAndDeleteBean;
import beans.RegisterInfoBean;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
import netframe.GetRetrofit;
import netframe.NetAddress;
import register.IrisRegisterClass;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.FormateUtils;
import utils.MediaPlayerUtils;
import utils.TimeUtil;


/**
 * A simple {@link Fragment} subclass.
 */
public class FactoryIrisRegisterFragment extends BaseFragment {
    @BindView(R.id.iv_factory_iris_rigister_back)
    ImageView ivBack;
    Unbinder unbinder;
    private IrisRegisterClass irisRegister;
    private MediaPlayer mediaPlayer;
    private RegisterInfoBean bean;
    private MyHandler allHandler;

    public FactoryIrisRegisterFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_supplier_iris_register, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initView() {
        super.initView();
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        bean = (RegisterInfoBean) getArguments().getSerializable(Constants.BASE_IRIS_REGISTER_FRAGMENT);
        irisRegister = new IrisRegisterClass(mContext) {
            @Override
            public void irisNetWork(String image) {
                updateUserInfo("set  LeftImg = '" + image +  "',ChangeTime = '" + TimeUtil.getMillisecondDate() + "', RightImg = '" + image + "',Enable = 'True',DelFlag=0,RoleInfoId = 5 where Name = '" + bean.getName() + "'");
            }

            @Override
            public void irisFailure() {
                Message message = allHandler.obtainMessage();
                message.what = HandlerConstant.REGISTER_FAILURE;
                message.obj = bean;
                allHandler.sendMessage(message);
            }
        };
    }

    //虹膜注册成功之后,将数据更新到数据库
    private void updateUserInfo(String sql) {
        Call<PutAndDeleteBean> call = GetRetrofit.getInstance().postUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<PutAndDeleteBean>() {
            @Override
            public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                PutAndDeleteBean body = response.body();
                if (body != null && body.getAffectRowCount() > 0) {
                    irisRegister.releaseIris();

//
//                    allHandler.sendEmptyMessage(HandlerConstant.REGISTER_SUCCESS);
                    getUserInfoId("select * from UserInfo where Name = '" + bean.getName() + "'");
                }
            }

            @Override
            public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {
                irisRegister.releaseIris();
            }
        });
    }

    private void getUserInfoId(String sql) {
        GetRetrofit.getInstance().getUserInfo2(NetAddress.token, NetAddress.machineCode, sql).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewUserInfoBean>() {
                    @Override
                    public void call(NewUserInfoBean userInfoBean) {
//                int userInfoId;
//                if (!bean.isOneFingerprintRegister()) {
                        int userInfoId = userInfoBean.getData().get(0).getID();
                        setFingerprintId("set FingerprintId = " + (10000 - userInfoId) + " where ID = " + userInfoId);
//                } else {
//                    userInfoId = userInfoBean.getData().get(0).getFingerprintId();
//                }
//                if (userInfoId > 0) {
//                    Message message = allHandler.obtainMessage();
//                    message.obj = fingerprintUserId;
//                    message.what = HandlerConstant.DELETE_FINGERPRINT_USER;
//                    allHandler.sendMessage(message);
//                }
                    }
                });
    }

    //设置第二个指纹的ID
    public void setFingerprintId(String sql) {
        Call<PutAndDeleteBean> call = GetRetrofit.getInstance().putUserInfo(NetAddress.token, NetAddress.machineCode, sql);
        call.enqueue(new Callback<PutAndDeleteBean>() {
            @Override
            public void onResponse(Call<PutAndDeleteBean> call, Response<PutAndDeleteBean> response) {
                registerSuccess();
            }

            @Override
            public void onFailure(Call<PutAndDeleteBean> call, Throwable t) {

            }
        });

    }

    private void registerSuccess() {
        MediaPlayerUtils.playSound(mContext,R.raw.register_success);
        bean.setPut(true);
        Message message = allHandler.obtainMessage();
        message.what = HandlerConstant.REGISTER_SUCCESS;
        message.obj = bean;
        allHandler.sendMessage(message);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.iv_factory_iris_rigister_back)
    public void onViewClicked(View view) {
        switch (view.getId()){

            case R.id.iv_factory_iris_rigister_back :
                irisRegister.releaseIris();
                Message message = allHandler.obtainMessage();
                message.what = HandlerConstant.REGISTER_TYPE;
                message.obj = bean;
                allHandler.sendMessage(message);
                break;
        }
    }
}
